; (function (root, factory) {
    if (typeof exports === "object") {
        // CommonJS
        module.exports = exports = factory(require("js-audio-recorder"));
    } else if (typeof define === "function" && define.amd) {
        // AMD
        define("IatRecSdk", ["js-audio-recorder"], factory);
    } else {
        // Global (browser)
        root.IatRecSdk = factory(root.Recorder);
    }
}(this, function (Recorder) {
    var IatRecSdk = IatRecSdk || function (cfg) {
        var config = cfg || {
            "scUrl": "ws://172.31.187.27:12321/aimed/v1/saber/iat/ws",
            "frameSize": 1280,
            "common": {
                "app_id": "MIME1000"
            },
            "business": {
                "domain": "iat",
                "language": "zh_cn"
            },
            "data": {
                "format": "audio/L16;rate=16000",
                "encoding": "raw"
            }
        };
        //上传录音每帧大小
        var frameSize = config.frameSize || 1280;

        //定时发送间隔时间，单位毫秒
        var intervalTime = config.intervalTime || 20;

        var recConfig = config.recConfig || {
            sampleBits: 16,
            sampleRate: 16000,
            numChannels: 1,
            compiling: true
        };

        //录音控件
        var recorder;

        //音频上传状态
        var status = 0;

        //录音队列
        var queue = [];

        //webSocket
        var ws;

        var onMessageFun;

        //定时任务
        var interval;

        //webSocket接收消息事件
        function ws_onMessage(e) {
            if (e.data) {
                var json = JSON.parse(e.data);
                if (json && json.code == 0) {
                    if (json.data && null != json.data.status && json.data.status == 2) {
                        //当返回最后一帧时，关闭webSocket连接
                        end();
                    }
                } else {
                    end();
                }
            }
            ws_onMessageCB(e);
        }

        function ws_onMessageCB(e) {
            if (typeof onMessageFun === "function") {
                onMessageFun(e);
            }
        }

        function end() {
            clearInterval(interval);
            //销毁录音控件
            if (recorder) {
                recorder.stop();
                recorder.destroy().then(function () {
                    recorder = null;
                });
            }
            if (ws) {
                ws.close();
                ws = null;
            }
            queue = [];
        }

        this.start = function (messageFun) {
            onMessageFun = messageFun;
            //重置状态
            status = 0;
            queue = [];
            //初始化录音控件
            recorder = new Recorder(recConfig);
            //录音数据回调
            recorder.onprogress = function (params) {
                var data = recorder.getNextData();
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        //在队列中追加录音数据
                        queue.push(...new Uint8Array(data[i].buffer));
                    }
                }
            }
            var recPromise = recorder.start();

            recPromise.then(() => {
                startWS();
            }
                , (error) => {
                    end();
                    var data = {
                        "code": -2,
                        "message": "no recorder permission"
                    };
                    ws_onMessageCB({
                        "data": JSON.stringify(data)
                    });
                }
            );

            return recPromise;
        }

        this.stop = function (forceStop) {
            if (forceStop) {
                onMessageFun = null;
                end();
            } else {
                //销毁录音控件
                if (recorder) {
                    recorder.stop();
                    recorder.destroy().then(function () {
                        recorder = null;
                    });
                }
                //将音频上传状态置为2，也就是最后一帧
                status = 2;
            }
        }

        this.getRecorder = function () {
            return recorder;
        }

        function startWS() {
            //初始化webSocket
            ws = new WebSocket(config.scUrl);
            ws.onopen = ws_onRecOpen;
            ws.onmessage = ws_onMessage;
            ws.onclose = function (e) { }
            ws.onerror = function (e) {
                end();
                var data = {
                    "code": -1,
                    "message": "WebSocket fall"
                };
                ws_onMessageCB({
                    "data": JSON.stringify(data)
                });
            }
        }

        //文件webSocket连接成功事件
        function ws_onRecOpen() {
            interval = setInterval(function () {
                //最后一帧
                if (status == 2) {
                    clearInterval(interval);
                    var data = {};
                    data.status = 2;
                    data.format = config.data.format;
                    data.encoding = config.data.encoding;
                    data.audio = "";
                    var frame = {};
                    frame.data = data;
                    if (ws && ws.readyState == WebSocket.OPEN) {
                        ws.send(JSON.stringify(frame));
                    }
                    return;
                }
                var datas = null;
                //console.log(queue.length);
                if (queue.length > frameSize) {
                    datas = queue.splice(0, frameSize);
                }
                if (datas && datas.length > 0) {
                    //首帧
                    if (status == 0) {
                        var data = {};
                        data.status = 0;
                        data.format = config.data.format;
                        data.encoding = config.data.encoding;
                        data.audio = window.btoa(String.fromCharCode(...datas));
                        var frame = {};
                        frame.common = config.common;
                        frame.business = config.business;
                        frame.data = data;
                        status = 1;
                        if (ws && ws.readyState == WebSocket.OPEN) {
                            ws.send(JSON.stringify(frame));
                        }
                    }//中间帧
                    else if (status == 1) {
                        var data = {};
                        data.status = 1;
                        data.format = config.data.format;
                        data.encoding = config.data.encoding;
                        data.audio = window.btoa(String.fromCharCode(...datas));
                        var frame = {};
                        frame.data = data;
                        if (ws && ws.readyState == WebSocket.OPEN) {
                            ws.send(JSON.stringify(frame));
                        }
                    }
                }
            }, intervalTime);
        }
    };
    return IatRecSdk;
}));
